package karileet.meeting.profile.provider;

import karileet.meeting.profile.MeetingProfile;
import karileet.meeting.profile.ProfileConf;
import karileet.meeting.profile.R;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

/**
 * Class for widget button functionality. It also updates button graphics
 * depending on current state (widget is added while app is active)
 * TODO: "no longer needed" error avoiding. Android tends to kill app instance
 * every once in a while
 * 
 * @author markus karileet
 */
public class WidgetProvider extends AppWidgetProvider {
	public static String WIDGET_TOGGLE = "Toggle";

	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		Log.d(ProfileConf.APP, "Received widget onUpdate call");
		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			Intent intent = new Intent(context,
					WidgetProvider.class);
			intent.setAction(WIDGET_TOGGLE);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
					0, intent, 0);
			RemoteViews views = new RemoteViews(context.getPackageName(),
					R.layout.widget);
			views.setOnClickPendingIntent(R.id.button1, pendingIntent);
			appWidgetManager.updateAppWidget(appWidgetId, views);
			ProfileConf state = new ProfileConf(context);
			//update button graphics
			if (state.isProfileEnabled()) {
				views.setImageViewResource(R.id.button1, R.drawable.mpbtn3_down);
			} else {
				views.setImageViewResource(R.id.button1, R.drawable.mpbtn3_up);
			}
			appWidgetManager.updateAppWidget(appWidgetId, views);
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d(ProfileConf.APP, "Received widget button press");
		super.onReceive(context, intent);
		if (intent.getAction().equals(WIDGET_TOGGLE)) {
			ProfileConf state = new ProfileConf(context);
			MeetingProfile mp = new MeetingProfile(context);
			RemoteViews views = new RemoteViews(context.getPackageName(),
					R.layout.widget);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
					0, intent, 0);
			views.setOnClickPendingIntent(R.id.button1, pendingIntent);
			if (state.isProfileEnabled()) {
				mp.disable();
				Log.d(ProfileConf.APP, "Drawing button-up graphic");
				views.setImageViewResource(R.id.button1, R.drawable.mpbtn3_up);
			} else {
				mp.enable();
				Log.d(ProfileConf.APP, "Drawing button-down graphic");
				views.setImageViewResource(R.id.button1, R.drawable.mpbtn3_down);
			}
			ComponentName widget = new ComponentName(context,
					WidgetProvider.class);
			(AppWidgetManager.getInstance(context)).updateAppWidget(widget,
					views);
		}
	}
	
}
